//
//  OAuthViewController.swift
//  LBWeibo
//
//  Created by 李博 on 15/6/25.
//  Copyright © 2015年 libo. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController,UIWebViewDelegate {
    
    //定义常量
    // 0. 定义常量
    private let WB_Client_ID = "31259537"
    private let WB_Redirect_URI = "http://www.baidu.com"
    private let WB_App_Secret = "7bac4cdb0d8f829d11d7e4f3c71b339c"
    
    var webView: UIWebView?
    
    override func loadView() {
        
        webView = UIWebView()
        webView!.delegate = self
        view = webView
        
        //设置nav的信息
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
    }
    ///关闭当前窗口
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //加载授权页面
        loadOAthPage()
    }
    
    private func loadOAthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URI)"
        let url = NSURL(string: urlString)!
        
        webView?.loadRequest(NSURLRequest(URL: url))
        

    }
    
    //MARK: --UIWebViewDelegate
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //url的完整字符串
        let urlString = request.URL!.absoluteString
        
        //print(urlString)
        
        //如果不是回调的url,就继续加载
        
        if !(urlString.hasPrefix(WB_Redirect_URI)) {
            print("继续加载")
            return true
        }
        //如果是回调地址，需要根据url中的内容，判断是否有授权码
        print("需要判断")
        //获取请求url中的查询字符串
        let query = request.URL!.query!
        let codeStr = "code="
        
        //let fromlen = codeStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
        //print(fromlen)
        //print((codeStr as NSString).length)
        
        if query.hasPrefix(codeStr) {
            let code = (query as NSString).substringFromIndex((codeStr as NSString).length)
            //print("授权码：\(code)")
            
            loadAccessToken(code)
            
        }else{
            print("取消授权。")
            //关闭chuangko
            close()
        }
        return false
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("正在加载中。。。")
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    ///使用授权码加载token
    private func loadAccessToken(code:String) {
        
        let urlString = "oauth2/access_token"
        
        //请求参数
        let params = ["client_id":WB_Client_ID,
                    "client_secret":WB_App_Secret,
                    "grant_type":"authorization_code",
                    "code":code,
                    "redirect_uri":WB_Redirect_URI]
        
        //发起网络请求
        //设置数据响应格式- 二进制
        //NetworkTools.sharedNetworkTools().responseSerializer = AFHTTPResponseSerializer()
        
        NetworkTools.sharedNetworkTools().POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            //加载用户信息
            UserAccount(dict: JSON as! [String : AnyObject]).loadUserInfo { (account, error) -> () in
            
                if account != nil {
                    //1. 设置全局的用户账号
                    sharedUserAccount = account
                    //2. 发送通知
                    NSNotificationCenter.defaultCenter().postNotificationName(LBSwitchRootVCNotification, object: false)
                    //3. 关闭当前控制器
                    self.close()
                    
                    return
                }
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("网络不给力。。")
        }
    }
    
    deinit {
        print("------------------88-------------------")
    }

}
